<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flux 图片编辑器</title>

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }

        .header p {
            opacity: 0.9;
            font-size: 1.1rem;
        }

        .form-container {
            padding: 40px;
        }

        .form-group {
            margin-bottom: 25px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #374151;
        }

        input[type="url"],
        input[type="text"],
        select,
        textarea {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        input[type="url"]:focus,
        input[type="text"]:focus,
        select:focus,
        textarea:focus {
            outline: none;
            border-color: #4f46e5;
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }

        textarea {
            resize: vertical;
            min-height: 100px;
            padding-right: 80px;
            /* 为翻译按钮留出空间 */
        }

        .submit-btn {
            width: 100%;
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            color: white;
            border: none;
            padding: 16px;
            border-radius: 8px;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(79, 70, 229, 0.3);
        }

        .submit-btn:disabled {
            background: #9ca3af;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .spinner {
            border: 4px solid #f3f4f6;
            border-top: 4px solid #4f46e5;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        .result {
            display: none;
            margin-top: 30px;
            padding: 20px;
            background: #f9fafb;
            border-radius: 8px;
        }

        .result h3 {
            margin-bottom: 15px;
            color: #374151;
        }

        .image-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }

        .result-image {
            width: 100%;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .result-image-container {
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .result-image-buttons {
            display: flex;
            gap: 8px;
            margin-top: 10px;
            opacity: 1;
        }

        .reuse-btn,
        .download-btn {
            padding: 6px 12px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .reuse-btn {
            background: #4f46e5;
            color: white;
        }

        .reuse-btn:hover {
            background: #4338ca;
            transform: translateY(-1px);
        }

        .download-btn {
            background: #059669;
            color: white;
        }

        .download-btn:hover {
            background: #047857;
            transform: translateY(-1px);
        }

        .error {
            display: none;
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: #dc2626;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
        }

        .image-input-section {
            border: 2px dashed #d1d5db;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            transition: border-color 0.3s ease;
            margin-bottom: 25px;
        }

        .image-input-section.dragover {
            border-color: #4f46e5;
            background-color: #f8fafc;
        }

        .image-input-section.paste-ready {
            border-color: #059669;
            background-color: #f0fdf4;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {

            0%,
            100% {
                opacity: 1;
            }

            50% {
                opacity: 0.8;
            }
        }

        .upload-area {
            margin-bottom: 15px;
        }

        .upload-btn {
            background: #4f46e5;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
            transition: background-color 0.3s ease;
        }

        .upload-btn:hover {
            background: #4338ca;
        }

        .file-input {
            display: none;
        }

        .url-input-container {
            display: flex;
            gap: 10px;
            align-items: center;
            margin-top: 15px;
        }

        .url-input {
            flex: 1;
        }

        .preview-btn {
            background: #059669;
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            white-space: nowrap;
        }

        .preview-btn:hover {
            background: #047857;
        }

        .image-preview {
            display: none;
            margin-top: 20px;
            text-align: center;
        }

        .preview-image {
            max-width: 100%;
            max-height: 300px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .preview-info {
            margin-top: 10px;
            color: #6b7280;
            font-size: 14px;
        }

        .clear-image {
            background: #dc2626;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            margin-top: 10px;
        }

        .clear-image:hover {
            background: #b91c1c;
        }

        .translate-btn {
            position: absolute;
            top: 12px;
            right: 12px;
            background: #059669;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            z-index: 10;
            transition: background-color 0.3s ease;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .translate-btn:hover {
            background: #047857;
        }

        .translate-btn:disabled {
            background: #9ca3af;
            cursor: not-allowed;
        }

        .translation-info {
            margin-top: 5px;
            color: #059669;
            font-size: 12px;
        }

        .translation-result-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }

        .translation-result-header label {
            margin-bottom: 0;
            color: #059669;
            font-weight: 600;
        }

        #translatedPrompt {
            min-height: 100px;
            resize: vertical;
            border-color: #059669;
            background-color: #f0fdf4;
        }

        #translatedPrompt:focus {
            border-color: #047857;
            box-shadow: 0 0 0 3px rgba(5, 150, 105, 0.1);
        }

        .translation-note {
            margin-top: 8px;
            color: #059669;
            font-size: 12px;
        }

        .clear-translation-btn {
            background: #dc2626;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            transition: background-color 0.3s ease;
        }

        .clear-translation-btn:hover {
            background: #b91c1c;
        }

        .row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .prompt-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 25px;
        }

        .prompt-left,
        .prompt-right {
            margin-bottom: 0;
        }

        @media (max-width: 768px) {
            .row {
                grid-template-columns: 1fr;
            }

            .prompt-row {
                grid-template-columns: 1fr;
                gap: 15px;
            }

            .header h1 {
                font-size: 2rem;
            }

            .form-container {
                padding: 20px;
            }

            .url-input-container {
                flex-direction: column;
            }

            .preview-btn {
                width: 100%;
            }



            .translation-result-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
            }

            .clear-translation-btn {
                align-self: flex-end;
            }

            textarea {
                padding-right: 16px;
                /* 移动端恢复正常内边距 */
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="header">
            <h1>🎨 Flux 图片编辑器</h1>
            <p>使用 AI 技术编辑和生成图片</p>
        </div>

        <div class="form-container">
            <form id="imageEditForm">
                <div class="form-group">
                    <label>选择图片 *</label>
                    <div class="image-input-section" id="imageInputSection">
                        <div class="upload-area">
                            <p style="margin-bottom: 15px; color: #6b7280;">
                                拖拽图片到此处、点击上传或按 Ctrl+V 粘贴剪贴板图片
                            </p>
                            <div style="display: flex; gap: 10px; justify-content: center; flex-wrap: wrap;">
                                <button type="button" class="upload-btn"
                                    onclick="document.getElementById('fileInput').click()">
                                    📁 选择文件
                                </button>
                                <button type="button" class="upload-btn" onclick="pasteFromClipboard()">
                                    📋 粘贴图片
                                </button>
                            </div>
                            <input type="file" id="fileInput" class="file-input" accept="image/*">
                        </div>

                        <div style="margin: 15px 0; color: #9ca3af;">或者</div>

                        <div class="url-input-container">
                            <input type="url" id="imageUrl" class="url-input"
                                placeholder="输入图片 URL: https://example.com/image.jpg">
                            <button type="button" class="preview-btn" id="previewBtn">预览</button>
                        </div>
                    </div>

                    <div class="image-preview" id="imagePreview">
                        <img id="previewImage" class="preview-image" alt="图片预览">
                        <div class="preview-info" id="previewInfo"></div>
                        <button type="button" class="clear-image" id="clearImage">清除图片</button>
                    </div>
                </div>

                <!-- 提示词左右排列区域 -->
                <div class="prompt-row">
                    <div class="form-group prompt-left">
                        <label for="prompt">原提示词 *</label>
                        <div style="position: relative;">
                            <textarea id="prompt" name="prompt" required
                                placeholder="描述你想要对图片进行的编辑，例如：将背景改为蓝天白云"></textarea>
                            <button type="button" class="translate-btn" id="translateBtn" title="翻译为英文" style="position: absolute; top: 8px; right: 8px; z-index: 10;">
                                🌐 翻译
                            </button>
                        </div>
                        <div class="translation-info" id="translationInfo" style="display: none;">
                            <small>已翻译为英文</small>
                        </div>
                    </div>

                    <!-- 翻译结果显示区域 -->
                    <div class="form-group prompt-right" id="translationSection">
                        <label for="translatedPrompt">翻译后的提示词（可编辑）</label>
                        <div style="position: relative;">
                            <textarea id="translatedPrompt" name="translatedPrompt" placeholder="翻译结果将显示在这里，您可以进行修改"></textarea>
                            <button type="button" class="clear-translation-btn" id="clearTranslationBtn" title="清除翻译结果" style="position: absolute; top: 8px; right: 8px; z-index: 10;">
                                ✕ 清除
                            </button>
                        </div>
                        <div class="translation-note">
                            <small>💡 提交时将使用此翻译后的提示词，您可以随时修改</small>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="form-group">
                        <label for="modelType">模型类型</label>
                        <select id="modelType" name="modelType">
                            <option value="flux-pro">Flux Pro</option>
                            <option value="flux-max">Flux Max</option>
                            <option value="gpt-image">GPT Image</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="aspectRatio">宽高比</label>
                        <select id="aspectRatio" name="aspectRatio">
                            <option value="original">保持原比例</option>
                            <option value="1:1">1:1 (正方形)</option>
                            <option value="16:9">16:9 (宽屏)</option>
                            <option value="9:16">9:16 (竖屏)</option>
                            <option value="4:3">4:3 (标准)</option>
                            <option value="3:4">3:4 (竖版标准)</option>
                        </select>
                    </div>
                </div>

                <button type="submit" class="submit-btn" id="submitBtn">
                    开始编辑图片
                </button>
            </form>

            <div class="loading" id="loading">
                <div class="spinner"></div>
                <p>正在处理图片，请稍候...</p>
            </div>

            <div class="error" id="error"></div>

            <div class="result" id="result">
                <h3>编辑结果</h3>
                <div class="image-grid" id="imageGrid"></div>
            </div>
        </div>
    </div>

    <script>
        const API_KEY = 'sk-7vylVCM3AHsxeIOeCb11BfB235314eD1B0D9Fe21F888B1De';
        const BASE_URL = 'https://api.laozhang.ai/v1';
        const GLM_API_KEY = 'ac7b5eeff233470e99d1a5d181477ed1.9MzNx1RWZY4z8xdx';
        const GLM_BASE_URL = 'https://open.bigmodel.cn/api/paas/v4';

        let currentImageUrl = '';
        let uploadedFile = null;

        // 初始化事件监听器
        document.addEventListener('DOMContentLoaded', function () {
            initializeEventListeners();
        });

        function initializeEventListeners() {
            // 文件上传
            document.getElementById('fileInput').addEventListener('change', handleFileUpload);

            // URL 预览
            document.getElementById('previewBtn').addEventListener('click', handleUrlPreview);

            // 清除图片
            document.getElementById('clearImage').addEventListener('click', clearImage);

            // 翻译按钮
            document.getElementById('translateBtn').addEventListener('click', handleTranslate);

            // 清除翻译按钮
            document.getElementById('clearTranslationBtn').addEventListener('click', clearTranslation);

            // 拖拽上传
            const imageInputSection = document.getElementById('imageInputSection');
            imageInputSection.addEventListener('dragover', handleDragOver);
            imageInputSection.addEventListener('dragleave', handleDragLeave);
            imageInputSection.addEventListener('drop', handleDrop);

            // 剪贴板粘贴支持
            document.addEventListener('paste', handlePaste);
            document.addEventListener('keydown', handleKeyDown);

            // 表单提交
            document.getElementById('imageEditForm').addEventListener('submit', handleFormSubmit);
        }

        async function handleFileUpload(e) {
            const file = e.target.files[0];
            if (file) {
                uploadedFile = file;
                await previewUploadedFile(file);
            }
        }

        async function previewUploadedFile(file) {
            if (!file.type.startsWith('image/')) {
                showError('请选择有效的图片文件');
                return;
            }

            const reader = new FileReader();
            reader.onload = function (e) {
                currentImageUrl = e.target.result;
                showImagePreview(currentImageUrl, `文件: ${file.name} (${formatFileSize(file.size)})`);
            };
            reader.readAsDataURL(file);
        }

        async function handleUrlPreview() {
            const url = document.getElementById('imageUrl').value.trim();
            if (!url) {
                showError('请输入图片 URL');
                return;
            }

            try {
                // 验证 URL 是否为有效图片
                const img = new Image();
                img.onload = function () {
                    currentImageUrl = url;
                    uploadedFile = null; // 清除上传的文件
                    showImagePreview(url, `URL: ${url}`);
                };
                img.onerror = function () {
                    showError('无法加载图片，请检查 URL 是否正确');
                };
                img.src = url;
            } catch (error) {
                showError('URL 格式不正确');
            }
        }

        async function showImagePreview(src, info) {
            const previewDiv = document.getElementById('imagePreview');
            const previewImage = document.getElementById('previewImage');
            const previewInfo = document.getElementById('previewInfo');

            previewImage.src = src;

            // 获取图片尺寸信息
            const img = new Image();
            img.onload = async function () {
                const width = this.naturalWidth;
                const height = this.naturalHeight;
                const aspectRatio = await getImageAspectRatio(src);
                const sizeInfo = `${width} × ${height} (${aspectRatio})`;
                previewInfo.textContent = `${info} - ${sizeInfo}`;
            };
            img.onerror = function () {
                previewInfo.textContent = info;
            };
            img.src = src;

            previewDiv.style.display = 'block';
            hideError();
        }

        function clearImage() {
            currentImageUrl = '';
            uploadedFile = null;
            document.getElementById('imageUrl').value = '';
            document.getElementById('fileInput').value = '';
            document.getElementById('imagePreview').style.display = 'none';
        }

        function handleDragOver(e) {
            e.preventDefault();
            e.currentTarget.classList.add('dragover');
        }

        function handleDragLeave(e) {
            e.preventDefault();
            e.currentTarget.classList.remove('dragover');
        }

        function handleDrop(e) {
            e.preventDefault();
            e.currentTarget.classList.remove('dragover');

            // 处理文件拖拽
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                const file = files[0];
                if (file.type.startsWith('image/')) {
                    uploadedFile = file;
                    document.getElementById('fileInput').files = files;
                    previewUploadedFile(file);
                    return;
                }
            }

            // 处理图片数据拖拽（如从网页拖拽图片）
            const items = e.dataTransfer.items;
            if (items) {
                for (let i = 0; i < items.length; i++) {
                    const item = items[i];

                    // 处理图片文件
                    if (item.kind === 'file' && item.type.startsWith('image/')) {
                        const file = item.getAsFile();
                        if (file) {
                            uploadedFile = file;
                            previewUploadedFile(file);
                            return;
                        }
                    }

                    // 处理图片 URL
                    if (item.kind === 'string' && item.type === 'text/uri-list') {
                        item.getAsString((url) => {
                            if (url && (url.startsWith('http') || url.startsWith('data:image'))) {
                                document.getElementById('imageUrl').value = url;
                                handleUrlPreview();
                            }
                        });
                        return;
                    }
                }
            }
        }

        // 剪贴板粘贴处理
        async function handlePaste(e) {
            const items = e.clipboardData?.items;
            if (!items) return;

            for (let i = 0; i < items.length; i++) {
                const item = items[i];

                // 处理图片文件
                if (item.kind === 'file' && item.type.startsWith('image/')) {
                    e.preventDefault();
                    const file = item.getAsFile();
                    if (file) {
                        uploadedFile = file;
                        await previewUploadedFile(file);
                        showPasteSuccess();
                    }
                    return;
                }

                // 处理图片 URL
                if (item.kind === 'string' && item.type === 'text/plain') {
                    item.getAsString((text) => {
                        if (text && (text.startsWith('http') && (text.includes('.jpg') || text.includes('.png') || text.includes('.gif') || text.includes('.webp')))) {
                            e.preventDefault();
                            document.getElementById('imageUrl').value = text;
                            handleUrlPreview();
                            showPasteSuccess();
                        }
                    });
                    return;
                }
            }
        }

        // 键盘快捷键处理
        function handleKeyDown(e) {
            // Ctrl+V 或 Cmd+V 粘贴提示
            if ((e.ctrlKey || e.metaKey) && e.key === 'v') {
                const imageInputSection = document.getElementById('imageInputSection');
                imageInputSection.classList.add('paste-ready');
                setTimeout(() => {
                    imageInputSection.classList.remove('paste-ready');
                }, 2000);
            }
        }

        // 手动粘贴按钮
        async function pasteFromClipboard() {
            try {
                const clipboardItems = await navigator.clipboard.read();

                for (const clipboardItem of clipboardItems) {
                    for (const type of clipboardItem.types) {
                        if (type.startsWith('image/')) {
                            const blob = await clipboardItem.getType(type);
                            const file = new File([blob], `pasted-image.${type.split('/')[1]}`, { type });
                            uploadedFile = file;
                            await previewUploadedFile(file);
                            showPasteSuccess();
                            return;
                        }
                    }
                }

                // 如果没有图片，尝试读取文本（可能是图片URL）
                try {
                    const text = await navigator.clipboard.readText();
                    if (text && (text.startsWith('http') && (text.includes('.jpg') || text.includes('.png') || text.includes('.gif') || text.includes('.webp')))) {
                        document.getElementById('imageUrl').value = text;
                        handleUrlPreview();
                        showPasteSuccess();
                        return;
                    }
                } catch (textError) {
                    console.log('无法读取剪贴板文本');
                }

                showError('剪贴板中没有找到图片或图片URL');
            } catch (error) {
                console.error('读取剪贴板失败:', error);
                showError('无法访问剪贴板，请确保已授予权限或使用 Ctrl+V 粘贴');
            }
        }

        // 显示粘贴成功提示
        function showPasteSuccess() {
            const successMsg = document.createElement('div');
            successMsg.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #059669;
                color: white;
                padding: 12px 20px;
                border-radius: 8px;
                z-index: 1000;
                font-size: 14px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            `;
            successMsg.textContent = '✅ 图片已从剪贴板粘贴成功';
            document.body.appendChild(successMsg);

            setTimeout(() => {
                if (document.body.contains(successMsg)) {
                    document.body.removeChild(successMsg);
                }
            }, 3000);
        }

        async function handleFormSubmit(e) {
            e.preventDefault();

            if (!currentImageUrl) {
                showError('请先选择或上传图片');
                return;
            }

            const formData = new FormData(e.target);
            let imageUrl = currentImageUrl;
            let originalPrompt = formData.get('prompt');

            // 检查是否有翻译后的提示词
            const translatedPromptTextarea = document.getElementById('translatedPrompt');
            const translatedPrompt = translatedPromptTextarea.value.trim();

            if (!originalPrompt || originalPrompt.trim() === '') {
                showError('请输入编辑提示词');
                return;
            }

            // 如果是上传的文件，需要先转换为可访问的 URL
            if (uploadedFile) {
                // 这里可以上传到云存储或转换为 base64
                // 暂时使用 base64 格式
                imageUrl = currentImageUrl;
            }

            hideError();
            hideResult();

            // 优先使用翻译后的提示词，如果没有则自动翻译
            let finalPrompt = originalPrompt;

            if (translatedPrompt) {
                // 如果有翻译后的提示词，直接使用
                finalPrompt = translatedPrompt;
            } else if (!isEnglish(originalPrompt)) {
                // 如果没有翻译后的提示词且原始提示词不是英文，则自动翻译
                showTranslationLoading();
                try {
                    finalPrompt = await translateToEnglish(originalPrompt);
                    // 显示自动翻译结果
                    translatedPromptTextarea.value = finalPrompt;
                    document.getElementById('translationSection').style.display = 'block';
                } catch (error) {
                    console.warn("翻译失败，使用原始提示词:", error.message);
                    finalPrompt = originalPrompt;
                }
            }

            const data = {
                imageUrl: imageUrl,
                prompt: finalPrompt,
                aspectRatio: formData.get('aspectRatio'),
                modelType: formData.get('modelType')
            };

            // 显示图片处理加载状态
            showLoading('正在处理图片，请稍候...');

            try {
                const response = await editImage(data);
                showResult(response.editedImageUrls);
            } catch (error) {
                showError(error.message);
            } finally {
                hideLoading();
            }
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        async function getImageAspectRatio(imageUrl) {
            return new Promise((resolve) => {
                const img = new Image();
                img.onload = function () {
                    const width = this.naturalWidth;
                    const height = this.naturalHeight;

                    // 计算最大公约数来简化比例
                    const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
                    const divisor = gcd(width, height);
                    const aspectWidth = width / divisor;
                    const aspectHeight = height / divisor;

                    // 如果比例过于复杂，使用近似值
                    if (aspectWidth > 20 || aspectHeight > 20) {
                        const ratio = width / height;
                        if (Math.abs(ratio - 1) < 0.1) resolve("1:1");
                        else if (Math.abs(ratio - 16 / 9) < 0.1) resolve("16:9");
                        else if (Math.abs(ratio - 9 / 16) < 0.1) resolve("9:16");
                        else if (Math.abs(ratio - 4 / 3) < 0.1) resolve("4:3");
                        else if (Math.abs(ratio - 3 / 4) < 0.1) resolve("3:4");
                        else if (ratio > 1) resolve("16:9"); // 宽图默认16:9
                        else resolve("9:16"); // 高图默认9:16
                    } else {
                        resolve(`${aspectWidth}:${aspectHeight}`);
                    }
                };
                img.onerror = function () {
                    // 如果无法获取图片尺寸，默认使用1:1
                    resolve("1:1");
                };
                img.src = imageUrl;
            });
        }

        async function handleTranslate() {
            const promptTextarea = document.getElementById('prompt');
            const translateBtn = document.getElementById('translateBtn');
            const translationSection = document.getElementById('translationSection');
            const translatedPromptTextarea = document.getElementById('translatedPrompt');
            const originalText = promptTextarea.value.trim();

            if (!originalText) {
                showError('请先输入提示词');
                return;
            }

            // 检查是否已经是英文
            if (isEnglish(originalText)) {
                showError('提示词已经是英文，无需翻译');
                return;
            }

            translateBtn.disabled = true;
            translateBtn.textContent = '翻译中...';
            hideError();

            try {
                const translatedText = await translateToEnglish(originalText);

                // 显示翻译后的提示词（可编辑）
                translatedPromptTextarea.value = translatedText;

                // 显示翻译区域
                translationSection.style.display = 'block';

                // 隐藏原来的翻译信息
                document.getElementById('translationInfo').style.display = 'none';

            } catch (error) {
                showError(`翻译失败: ${error.message}`);
            } finally {
                translateBtn.disabled = false;
                translateBtn.textContent = '🌐 翻译';
            }
        }

        function clearTranslation() {
            const translationSection = document.getElementById('translationSection');
            const translatedPromptTextarea = document.getElementById('translatedPrompt');

            // 清空翻译内容
            translatedPromptTextarea.value = '';

            // 隐藏翻译区域
            translationSection.style.display = 'none';
        }

        function isEnglish(text) {
            // 简单检测是否为英文（主要包含英文字符）
            const englishRegex = /^[a-zA-Z0-9\s\.,!?;:'"()\-_]+$/;
            return englishRegex.test(text);
        }

        async function translateToEnglish(text) {
            const url = `${GLM_BASE_URL}/chat/completions`;
            const headers = {
                'Authorization': `Bearer ${GLM_API_KEY}`,
                'Content-Type': 'application/json'
            };

            const requestBody = {
                model: 'glm-4-flash',
                messages: [
                    {
                        role: 'system',
                        content: '你是一个专业的翻译助手，专门将中文翻译成英文。请将用户输入的中文文本翻译成自然、准确的英文，特别适合用于AI图片生成的提示词。只返回翻译结果，不要添加任何解释。'
                    },
                    {
                        role: 'user',
                        content: text
                    }
                ],
                thinking: {
                    type: 'enabled'
                },
                max_tokens: 4096,
                temperature: 0.6
            };

            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: headers,
                    body: JSON.stringify(requestBody)
                });

                if (!response.ok) {
                    let errorMsg = `翻译API请求失败 (${response.status}): ${response.statusText}`;
                    try {
                        const errorData = await response.json();
                        if (errorData.error && errorData.error.message) {
                            errorMsg = `翻译失败: ${errorData.error.message}`;
                        }
                    } catch (e) {
                        // 使用默认错误消息
                    }
                    throw new Error(errorMsg);
                }

                const result = await response.json();

                if (!result.choices || result.choices.length === 0) {
                    throw new Error('翻译API没有返回有效结果');
                }

                const translatedText = result.choices[0].message.content.trim();
                if (!translatedText) {
                    throw new Error('翻译结果为空');
                }

                return translatedText;
            } catch (error) {
                console.error('翻译错误:', error);
                throw error;
            }
        }

        async function editImage(data) {
            const { imageUrl, prompt, aspectRatio, modelType } = data;

            if (modelType === 'gpt-image') {
                return await editImageWithGPTImage(imageUrl, prompt);
            } else {
                return await editImageWithFlux(imageUrl, prompt, aspectRatio, modelType);
            }
        }

        async function editImageWithFlux(imageUrl, prompt, aspectRatio = "1:1", modelType = "flux-pro") {
            const url = `${BASE_URL}/images/edits`;
            const headers = {
                Authorization: `Bearer ${API_KEY}`,
            };



            // 处理保持原比例的情况
            let finalAspectRatio = aspectRatio;
            if (aspectRatio === "original") {
                finalAspectRatio = await getImageAspectRatio(imageUrl);
            }

            const formData = new FormData();
            let model;
            if (modelType === "flux-pro") {
                model = "flux-kontext-pro";
            } else if (modelType === "flux-max") {
                model = "flux-kontext-max";
            } else {
                model = "flux-kontext-pro";
            }

            formData.append("model", model);
            formData.append("prompt", prompt);
            formData.append("n", "1");
            formData.append("aspect_ratio", finalAspectRatio);

            // 获取图片内容
            console.log("正在从 URL 获取图片...");
            let imageBuffer;
            let fileName;
            let contentType;

            if (imageUrl.startsWith('data:')) {
                // 处理 base64 图片
                const base64Data = imageUrl.split(',')[1];
                imageBuffer = Uint8Array.from(atob(base64Data), c => c.charCodeAt(0));
                fileName = "uploaded_image.png";
                contentType = "image/png";
            } else {
                // 处理 URL 图片
                const imageResponse = await fetch(imageUrl);
                if (!imageResponse.ok) {
                    throw new Error(`从 URL 获取图片失败: ${imageResponse.statusText}`);
                }
                imageBuffer = await imageResponse.arrayBuffer();
                fileName = imageUrl.split('/').pop() || "image.png";
                contentType = imageResponse.headers.get("content-type") || "image/png";
            }

            const blob = new Blob([imageBuffer], { type: contentType });
            formData.append("image", blob, fileName);

            try {
                console.log("正在发送 HTTP 请求...");
                const response = await fetch(url, {
                    method: "POST",
                    headers: headers,
                    body: formData,
                });

                console.log(`📡 响应状态码: ${response.status}`);

                if (!response.ok) {
                    let errorMsg = `API 请求失败 (${response.status}): ${response.statusText}`;
                    try {
                        const errorData = await response.json();
                        if (errorData.error && errorData.error.message) {
                            errorMsg = `API 请求失败 (${response.status}): ${errorData.error.message}`;
                        } else if (errorData.message) {
                            errorMsg = `API 请求失败 (${response.status}): ${errorData.message}`;
                        } else {
                            errorMsg = `API 请求失败 (${response.status}): ${JSON.stringify(errorData)}`;
                        }
                    } catch (jsonError) {
                        const text = await response.text();
                        errorMsg = `API 请求失败 (${response.status}): ${text}`;
                    }
                    throw new Error(errorMsg);
                }

                const result = await response.json();
                console.log("✅ API 响应成功。");

                if (!result.data || result.data.length === 0) {
                    throw new Error("API 没有返回图片数据。");
                }

                // 返回图片URL数组
                const imageUrls = result.data
                    .map((imageData) => {
                        if (imageData.url) {
                            return imageData.url;
                        } else if (imageData.b64_json) {
                            return `data:image/png;base64,${imageData.b64_json}`;
                        } else {
                            return null;
                        }
                    })
                    .filter((url) => url !== null);

                if (imageUrls.length === 0) {
                    throw new Error("API 返回的数据中没有可用的图片URL或Base64数据。");
                }

                return { editedImageUrls: imageUrls };
            } catch (error) {
                console.error(`❌ 图片编辑失败: ${error instanceof Error ? error.message : String(error)}`);
                throw error;
            }
        }

        async function editImageWithGPTImage(imageUrl, prompt) {
            const url = `${BASE_URL}/chat/completions`;
            const headers = {
                Authorization: `Bearer ${API_KEY}`,
                "Content-Type": "application/json",
            };



            const requestBody = {
                model: "sora_image",
                messages: [
                    {
                        role: "user",
                        content: [
                            {
                                type: "text",
                                text: prompt,
                            },
                            {
                                type: "image_url",
                                image_url: {
                                    url: imageUrl,
                                },
                            },
                        ],
                    },
                ],
                n: 4,
            };

            try {
                console.log("正在发送 HTTP 请求...");
                const response = await fetch(url, {
                    method: "POST",
                    headers,
                    body: JSON.stringify(requestBody),
                });

                if (!response.ok) {
                    let errorMsg = `API 请求失败 (${response.status}): ${response.statusText}`;
                    try {
                        const errorData = await response.json();
                        if (errorData.error && errorData.error.message) {
                            errorMsg = `API 请求失败 (${response.status}): ${errorData.error.message}`;
                        } else if (errorData.message) {
                            errorMsg = `API 请求失败 (${response.status}): ${errorData.message}`;
                        } else {
                            errorMsg = `API 请求失败 (${response.status}): ${JSON.stringify(errorData)}`;
                        }
                    } catch (jsonError) {
                        const text = await response.text();
                        errorMsg = `API 请求失败 (${response.status}): ${text}`;
                    }
                    throw new Error(errorMsg);
                }

                const result = await response.json();
                console.log("✅ API 响应成功。");

                // 检查响应中是否包含图像数据
                if (!result.choices || result.choices.length === 0) {
                    throw new Error("API 没有返回图片数据。");
                }

                // 从响应中提取图像URL - 处理第一个choice
                const choice = result.choices[0];
                if (!choice.message || choice.message.content === undefined) {
                    throw new Error("API 返回的数据格式不符合预期。");
                }

                // 处理返回的 Markdown 格式字符串
                const contentStr = choice.message.content;
                console.log("contentStr", contentStr);

                // 使用正则表达式从 Markdown 中提取所有图片URL
                // 格式为: ![图片](https://example.com/image.png)
                const imageUrlRegex = /!\[.*?\]\((.*?)\)/g;
                let match;
                const imageUrls = [];

                // 逐个提取所有匹配的URL
                while ((match = imageUrlRegex.exec(contentStr)) !== null) {
                    if (match[1]) {
                        imageUrls.push(match[1]);
                    }
                }

                if (imageUrls.length === 0) {
                    throw new Error("在 API 响应中未找到可用的图片链接");
                }

                console.log("提取到的图片URL:", imageUrls);

                return { editedImageUrls: imageUrls };
            } catch (error) {
                console.error(`❌ GPT-Image 图片编辑失败: ${error instanceof Error ? error.message : String(error)}`);
                throw error;
            }
        }

        function showLoading(message = '正在处理图片，请稍候...') {
            const loadingDiv = document.getElementById('loading');
            const loadingText = loadingDiv.querySelector('p');
            loadingText.textContent = message;
            loadingDiv.style.display = 'block';
            document.getElementById('submitBtn').disabled = true;
        }

        function showTranslationLoading() {
            const loadingDiv = document.getElementById('loading');
            const loadingText = loadingDiv.querySelector('p');
            loadingText.innerHTML = '🌐 正在翻译提示词为英文...';
            loadingDiv.style.display = 'block';
            document.getElementById('submitBtn').disabled = true;

            // 禁用翻译按钮
            const translateBtn = document.getElementById('translateBtn');
            translateBtn.disabled = true;
            translateBtn.textContent = '翻译中...';
        }

        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
            document.getElementById('submitBtn').disabled = false;

            // 恢复翻译按钮
            const translateBtn = document.getElementById('translateBtn');
            translateBtn.disabled = false;
            translateBtn.textContent = '🌐 翻译';
        }

        function showError(message) {
            const errorDiv = document.getElementById('error');
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
        }

        function hideError() {
            document.getElementById('error').style.display = 'none';
        }

        function showResult(imageUrls) {
            const resultDiv = document.getElementById('result');
            const imageGrid = document.getElementById('imageGrid');

            // 清空之前的结果
            imageGrid.innerHTML = '';

            // 添加新的图片
            imageUrls.forEach((url, index) => {
                // 创建图片容器
                const imageContainer = document.createElement('div');
                imageContainer.className = 'result-image-container';

                // 创建图片元素
                const img = document.createElement('img');
                img.src = url;
                img.className = 'result-image';
                img.alt = '编辑后的图片';

                // 创建按钮容器
                const buttonContainer = document.createElement('div');
                buttonContainer.className = 'result-image-buttons';

                // 创建 Reuse 按钮
                const reuseBtn = document.createElement('button');
                reuseBtn.className = 'reuse-btn';
                reuseBtn.textContent = '🔄 重新编辑';
                reuseBtn.title = '使用此图片作为新的原图';
                reuseBtn.onclick = () => reuseImage(url);

                // 创建下载按钮
                const downloadBtn = document.createElement('button');
                downloadBtn.className = 'download-btn';
                downloadBtn.textContent = '💾 下载';
                downloadBtn.title = '下载此图片';
                downloadBtn.onclick = () => downloadImage(url, `edited_image_${index + 1}.png`);

                // 组装元素
                buttonContainer.appendChild(reuseBtn);
                buttonContainer.appendChild(downloadBtn);
                imageContainer.appendChild(img);
                imageContainer.appendChild(buttonContainer);
                imageGrid.appendChild(imageContainer);
            });

            resultDiv.style.display = 'block';
        }

        function hideResult() {
            document.getElementById('result').style.display = 'none';
        }

        function reuseImage(imageUrl) {
            // 清除当前图片
            clearImage();

            // 设置新的图片URL
            currentImageUrl = imageUrl;
            uploadedFile = null;

            // 显示预览
            showImagePreview(imageUrl, `重用图片: ${imageUrl.substring(0, 50)}...`);

            // 清空提示词，让用户输入新的编辑指令
            document.getElementById('prompt').value = '';
            document.getElementById('translationInfo').style.display = 'none';

            // 滚动到顶部
            window.scrollTo({ top: 0, behavior: 'smooth' });

            // 显示成功提示
            const successMsg = document.createElement('div');
            successMsg.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #059669;
                color: white;
                padding: 12px 20px;
                border-radius: 8px;
                z-index: 1000;
                font-size: 14px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            `;
            successMsg.textContent = '✅ 图片已设置为新的原图，请输入新的编辑提示词';
            document.body.appendChild(successMsg);

            // 3秒后移除提示
            setTimeout(() => {
                document.body.removeChild(successMsg);
            }, 3000);
        }

        function downloadImage(imageUrl, filename) {
            // 直接在新标签页打开图片URL进行下载
            window.open(imageUrl, '_blank');
        }


    </script>
</body>

</html>